<?php

namespace frontend\controllers;

use backend\models\Category;
use Yii;
use frontend\models\Cart;
use frontend\models\CartSearcher;
//use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \backend\models\Product;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

/**
 * CartController implements the CRUD actions for Cart model.
 */
//class CartController extends Controller
class CartController extends SuperController {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function beforeAction($action) {
        if (parent::beforeAction($action)) {
            if (\Yii::$app->user->isGuest) {
                return $this->redirect(Url::toRoute('site/login'));
            } else {
                
            }
            return TRUE;
        } else {
            return FALSE;
        };
    }

    /**
     * Lists all Cart models.
     * @return mixed
     */
    public function actionIndex() {
        $this->layout = 'layout2';
//        $searchModel = new CartSearcher();
//        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//
//        return $this->render('index', [
//                    'searchModel' => $searchModel,
//                    'dataProvider' => $dataProvider,
//        ]);
//        在superController获取了
//        $productModel = new Product();
//        $cartModel = new Cart();
//        $cartModel = $cartModel->find(['userId' => \Yii::$app->user->id]);
//        $count = $cartModel->count();
//        $cartModel = $cartModel->all();
//        $cartList = ArrayHelper::toArray($cartModel);
//        $cartTotal = 0;
//        for ($i = 0; $i < $count; $i++) {
//            $productModel = $productModel->findOne($cartList[$i]['productId']);
//            $cartList[$i]['productTitle'] = $productModel->title;
//            $cartList[$i]['productCover'] = $productModel->cover;
//            $cartList[$i]['productTotal'] = $cartList[$i]['price'] * $cartList[$i]['productnum'];
//            $cartTotal += $cartList[$i]['productTotal'];
//        }

        return $this->render('index', [
//                    'cartTotal' => $cartTotal,
//                    'cartList' => $cartList,
        ]);
    }

    /**
     * Displays a single Cart model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id) {
        return $this->render('view', [
                    'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Cart model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new Cart();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->cartId]);
        } else {
            return $this->render('create', [
                        'model' => $model,
            ]);
        }
    }

    public function actionAdd() {
        $model = new Cart();
        if (Yii::$app->request->isAjax) {
            $message = "success";
            $data = Yii::$app->request->post();
            $productId = $data['id'];
            $number = $data['number'];
            $userId = Yii::$app->user->id;
            $productModel = Product::findOne(["productId" => $productId]);
            if ($model = $model->findOne(['productId' => $productId, 'userId' => $userId])) {
                $model->productnum += $number;
                 $message = "exists";
            } else {
                $model = new Cart();
                $model->productId = $productId;
                $model->productnum = $number;
                $model->userId = $userId;
                $message = "success";
            }
//            return $productModel->saleprice;
            $model->price = $productModel->issale == 0 ? $productModel->saleprice : $productModel->price;
            if ($model->save()) {
                return $message;
            } else {
                $message = "error";
                return $message;
            }
        }
        return "error";
    }

    public function actionMinus() {
        if (Yii::$app->request->isAjax) {
            $data = Yii::$app->request->post();
            $productId = $data['id'];
            $number = $data['number'];
            $userId = Yii::$app->user->id;
            $model = Cart::findOne(['productId' => $productId, 'userId' => $userId]);
            $model->productnum -= $number;
            if ($model->save()) {
                return "success";
            } else {
                return "error";
            }
        }
        return "error";
    }

    public function actionRemove() {
        if (Yii::$app->request->isAjax) {
            $data = Yii::$app->request->post();
            $productId = $data['id'];
            $userId = Yii::$app->user->id;
            $model = Cart::findOne(['productId' => $productId, 'userId' => $userId]);
            if ($model->delete()) {
                return "success";
            } else {
                return "error";
            }
        }
        return "error";
    }

    /**
     * Updates an existing Cart model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->cartId]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Cart model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Cart model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Cart the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = Cart::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
